<template>
  <div class="documentation-container">
    <!-- 侧边导航 -->
    <nav class="sidebar">
      <div class="sidebar-header">
        <h3>📖 目录导航</h3>
      </div>
      <ul class="sidebar-nav">
        <li v-for="heading in headings" :key="heading.id">
          <a
            :href="`#${heading.id}`"
            @click.prevent="scrollToSection(heading.id)"
            :class="{
              active: activeSection === heading.id,
              [`nav-level-${heading.level}`]: true
            }"
          >
            {{ heading.icon }} {{ heading.text }}
          </a>
        </li>
      </ul>
    </nav>

    <!-- 滚动进度指示器 -->
    <div class="scroll-indicator">
      <div class="scroll-progress" :style="{ width: scrollProgress + '%' }"></div>
    </div>

    <!-- 主内容区域 -->
    <main class="main-content" ref="mainContent">
      <div class="content-wrapper">
        <div v-if="loading" class="loading-container" v-loading="true" element-loading-text="正在加载文档...">
          <div style="height: 200px; width: 100%;"></div>
        </div>
        <div v-else-if="error" class="error-container">
          <el-alert
            title="文档加载失败"
            :description="error"
            type="error"
            show-icon
          />
        </div>
        <div v-else class="markdown-content" v-html="renderedMarkdown"></div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 类型定义
interface Heading {
  id: string
  text: string
  level: number
  icon: string
}

// 响应式数据
const activeSection = ref('')
const scrollProgress = ref(0)
const mainContent = ref<HTMLElement>()
const loading = ref(true)
const error = ref('')
const renderedMarkdown = ref('')
const headings = ref<Heading[]>([])

// 备选的Markdown内容
const fallbackMarkdown = `666`

// 配置marked
const configureMarked = () => {
  // 自定义渲染器
  const renderer = new marked.Renderer()

  // 自定义标题渲染，添加id属性
  renderer.heading = function({ tokens, depth }: { tokens: any[], depth: number }) {
    const text = this.parser.parseInline(tokens)
    const id = text.replace(/[^\w\u4e00-\u9fa5]+/g, '')
    return `<h${depth} id="${id}">${text}</h${depth}>`
  }

  // 自定义图片渲染，处理相对路径
  renderer.image = function({ href, title, text }: { href: string, title?: string | null, text: string }) {
    // 如果是相对路径，添加正确的前缀
    if (href && !href.startsWith('http') && !href.startsWith('/')) {
      href = `/skill/about_md/8oIhXf/${href}`
    }
    return `<img src="${href}" alt="${text}" title="${title || ''}" class="doc-image" />`
  }

  marked.use({
    renderer,
    breaks: true,
    gfm: true
  })

  // 设置代码高亮
  marked.use({
    async: false,
    hooks: {
      preprocess(markdown: string) {
        return markdown
      },
      postprocess(html: string) {
        // 对代码块进行高亮处理
        const tempDiv = document.createElement('div')
        tempDiv.innerHTML = html
        const codeBlocks = tempDiv.querySelectorAll('pre code')
        codeBlocks.forEach((block) => {
          hljs.highlightElement(block as HTMLElement)
        })
        return tempDiv.innerHTML
      }
    }
  })
}

// 提取标题信息
const extractHeadings = (markdown: string): Heading[] => {
  const headingRegex = /^(#{1,6})\s+(.+)$/gm
  const headings: Heading[] = []
  const icons = ['🏠', '⚔️', '🎯', '🖥️', '🚀', '📋', '🎮']
  let iconIndex = 0

  let match
  while ((match = headingRegex.exec(markdown)) !== null) {
    const level = match[1].length
    const text = match[2].trim()
    const id = text.replace(/[^\w\u4e00-\u9fa5]+/g, '')

    headings.push({
      id,
      text,
      level,
      icon: icons[iconIndex % icons.length]
    })
    iconIndex++
  }

  return headings
}

// 加载Markdown文件
const loadMarkdownFile = async () => {
  try {
    loading.value = true
    error.value = ''

    // 尝试不同的文件路径
    const possiblePaths = [
      '/skill/about_md/8oIhXf/system-documentation.md',
      '/skill/about_md/8oIhXf/web搜索页面系统说明页.md',
      '/about_md/8oIhXf/system-documentation.md',
      '/about_md/8oIhXf/web搜索页面系统说明页.md'
    ]

    let response: Response | null = null
    let lastError: Error | null = null

    for (const path of possiblePaths) {
      try {
        response = await fetch(path)
        if (response.ok) {
          break
        }
      } catch (err) {
        lastError = err as Error
        continue
      }
    }

    let markdownText: string

    if (!response || !response.ok) {
      console.warn('无法加载外部Markdown文件，使用备选内容')
      markdownText = fallbackMarkdown
    } else {
      markdownText = await response.text()
    }

    // 提取标题
    headings.value = extractHeadings(markdownText)

    // 渲染Markdown
    const result = await marked.parse(markdownText)
    renderedMarkdown.value = typeof result === 'string' ? result : await result

    // 等待DOM更新后设置滚动监听
    await nextTick()
    setupScrollListener()

  } catch (err) {
    console.error('加载Markdown文件失败:', err)
    // 如果所有方法都失败，使用备选内容
    try {
      headings.value = extractHeadings(fallbackMarkdown)
      const result = await marked.parse(fallbackMarkdown)
      renderedMarkdown.value = typeof result === 'string' ? result : await result
      await nextTick()
      setupScrollListener()
    } catch (fallbackErr) {
      error.value = '文档加载失败，请刷新页面重试'
    }
  } finally {
    loading.value = false
  }
}

// 设置滚动监听
const setupScrollListener = () => {
  // 初始化当前章节
  highlightCurrentSection()
}

// 滚动到指定章节
const scrollToSection = (sectionId: string) => {
  console.log('尝试滚动到章节:', sectionId)
  const element = document.getElementById(sectionId)
  console.log('找到的元素:', element)

  if (element) {
    // 获取主内容区域
    const mainContentEl = mainContent.value
    if (mainContentEl) {
      // 计算相对于主内容区域的偏移
      const elementTop = element.offsetTop
      const offsetTop = elementTop - 80 // 留出一些顶部空间

      // 滚动主内容区域
      mainContentEl.scrollTo({
        top: offsetTop,
        behavior: 'smooth'
      })
    } else {
      // 备选方案：滚动整个窗口
      const offsetTop = element.offsetTop - 80
      window.scrollTo({
        top: offsetTop,
        behavior: 'smooth'
      })
    }
  } else {
    console.warn('未找到目标元素:', sectionId)
  }
}

// 更新滚动进度
const updateScrollProgress = () => {
  const mainContentEl = mainContent.value
  if (mainContentEl) {
    const scrollTop = mainContentEl.scrollTop
    const scrollHeight = mainContentEl.scrollHeight - mainContentEl.clientHeight
    const scrollPercent = scrollHeight > 0 ? (scrollTop / scrollHeight) * 100 : 0
    scrollProgress.value = Math.min(scrollPercent, 100)
  }
}

// 高亮当前章节
const highlightCurrentSection = () => {
  const mainContentEl = mainContent.value
  if (!mainContentEl) return

  const scrollTop = mainContentEl.scrollTop + 100
  const sectionIds = headings.value.map(h => h.id)

  for (let i = sectionIds.length - 1; i >= 0; i--) {
    const element = document.getElementById(sectionIds[i])
    if (element && scrollTop >= element.offsetTop) {
      activeSection.value = sectionIds[i]
      break
    }
  }
}

// 滚动事件处理
const handleScroll = () => {
  updateScrollProgress()
  highlightCurrentSection()
}

// 生命周期钩子
onMounted(async () => {
  configureMarked()
  await loadMarkdownFile()

  // 监听主内容区域的滚动事件
  const mainContentEl = mainContent.value
  if (mainContentEl) {
    mainContentEl.addEventListener('scroll', handleScroll)
  }

  updateScrollProgress()
})

onUnmounted(() => {
  const mainContentEl = mainContent.value
  if (mainContentEl) {
    mainContentEl.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
.documentation-container {
  display: flex;
  min-height: 90vh;
  background: #f8f9fa;
  position: relative;
  overflow: hidden; /* 防止整体页面滚动 */
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  width: 100%;
}

/* 侧边导航样式 */
.sidebar {
  position: fixed;
  top: 0;
  left: 200px; /* 考虑主菜单的宽度 */
  width: 280px;
  height: 90vh;
  background: white;
  border-right: 1px solid #e9ecef;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  overflow-y: auto;
}

.sidebar-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  border-bottom: 2px solid #007bff;
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.sidebar-nav {
  list-style: none;
  padding: 20px 0;
  margin: 0;
}

.sidebar-nav li {
  margin-bottom: 8px;
}

.sidebar-nav a {
  display: block;
  padding: 12px 20px;
  color: #666;
  text-decoration: none;
  border-radius: 0 25px 25px 0;
  margin-right: 20px;
  transition: all 0.2s ease;
  font-size: 14px;
  line-height: 1.4;
  cursor: pointer;
}

.sidebar-nav a:hover {
  background: #e3f2fd;
  color: #1976d2;
  transform: translateX(5px);
}

.sidebar-nav a.active {
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.sidebar-nav .nav-level-1 {
  font-weight: bold;
}

.sidebar-nav .nav-level-2 {
  padding-left: 30px;
  font-size: 13px;
}

.sidebar-nav .nav-level-3 {
  padding-left: 40px;
  font-size: 12px;
}

.sidebar-nav .nav-level-4,
.sidebar-nav .nav-level-5,
.sidebar-nav .nav-level-6 {
  padding-left: 50px;
  font-size: 12px;
}

/* 滚动进度指示器 */
.scroll-indicator {
  position: fixed;
  top: 0;
  left: 480px; /* 主菜单 + 侧边栏宽度 */
  right: 0;
  height: 4px;
  background: #e9ecef;
  z-index: 999;
}

.scroll-progress {
  height: 100%;
  background: linear-gradient(90deg, #007bff, #28a745);
  transition: width 0.1s ease;
  box-shadow: 0 0 10px rgba(0, 123, 255, 0.5);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  margin-left: 280px;
  padding: 0;
  height: 90vh;
  overflow-y: auto; /* 只有主内容区域可以滚动 */
  background: white;
}

/* 内容包装器 */
.content-wrapper {
  padding: 40px;
  min-height: 100%;
}

/* Markdown内容样式 */
.markdown-content {
  max-width: none;
  line-height: 1.8;
}

/* 标题样式 */
.markdown-content :deep(h1) {
  font-size: 2.5rem;
  color: #2c3e50;
  text-align: center;
  margin: 40px 0;
  padding: 40px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.markdown-content :deep(h2) {
  font-size: 1.8rem;
  color: #2c3e50;
  border-bottom: 3px solid #007bff;
  padding-bottom: 10px;
  margin: 40px 0 30px 0;
}

.markdown-content :deep(h3) {
  font-size: 1.4rem;
  color: #34495e;
  margin: 30px 0 20px 0;
}

.markdown-content :deep(h4) {
  font-size: 1.2rem;
  color: #5a6c7d;
  margin: 25px 0 15px 0;
}

/* 段落和文本样式 */
.markdown-content :deep(p) {
  margin-bottom: 15px;
  color: #555;
}

.markdown-content :deep(strong) {
  color: #2c3e50;
  font-weight: 600;
}

/* 列表样式 */
.markdown-content :deep(ol),
.markdown-content :deep(ul) {
  margin: 20px 0;
  padding-left: 30px;
}

.markdown-content :deep(li) {
  margin-bottom: 10px;
  line-height: 1.6;
}

/* 代码样式 */
.markdown-content :deep(code) {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  color: #d73a49;
  font-size: 0.9em;
}

.markdown-content :deep(pre) {
  background: #2d3748;
  color: #e2e8f0;
  padding: 20px;
  border-radius: 8px;
  margin: 20px 0;
  overflow-x: auto;
}

.markdown-content :deep(pre code) {
  background: none;
  color: inherit;
  padding: 0;
  font-size: 14px;
}

/* 图片样式 */
.markdown-content :deep(.doc-image) {
  max-width: 100%;
  height: auto;
  border-radius: 10px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
  display: block;
  margin: 25px auto;
}

.markdown-content :deep(.doc-image:hover) {
  transform: scale(1.02);
}

/* 引用样式 */
.markdown-content :deep(blockquote) {
  border-left: 4px solid #007bff;
  background: #f8f9fa;
  padding: 20px;
  margin: 20px 0;
  border-radius: 0 8px 8px 0;
}

/* 表格样式 */
.markdown-content :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.markdown-content :deep(th) {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.markdown-content :deep(tr:nth-child(even)) {
  background: #f9f9f9;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .sidebar {
    left: 64px; /* 收起状态的主菜单宽度 */
  }

  .scroll-indicator {
    left: 344px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    left: 0;
    width: 100%;
    transform: translateX(-100%);
  }

  .main-content {
    margin-left: 0;
  }

  .scroll-indicator {
    left: 0;
  }

  .markdown-content :deep(h1) {
    font-size: 2rem;
  }

  .content-wrapper {
    padding: 20px;
  }
}
</style>
